#coding:utf8
#
# Author: CMGS
# Created on 2011-1-18
#

from common import config as _conf
from utils.corn import PeriodicCallback as _corn

from content import update

class TaskPool(object):
    
    def __init__(self):
        self._taskList = {}
    
    def fork(self, url, time = _conf.RSS_UPDATE_TIME, now = False):
        # Maybe lots urls would make some problems
        self._taskList[url] = _corn(update, time, now, url = url)
        return True

    def startOne(self, url):
        c  = self._taskList.get(url, None) 
        if c is None or c.isRunning:
            return False
        c.start()
        return True

    def cancelOne(self, url):
        c  = self._taskList.get(url, None) 
        if c is None or c.isRunning:
            return False
        c.stop()
        return True
    
    def startAll(self):
        it = self._taskList.iteritems()        
        while True:
            try:
                t = it.next()
                c = t[1]
                if not c.isRunning:
                    c.start()
            except StopIteration:
                break
        return True
    
    def stopAll(self):
        it = self._taskList.iteritems()        
        while True:
            try:
                t = it.next()
                c = t[1]
                if c.isRunning:
                    c.stop()
            except StopIteration:
                break
        return True
